//
//  RLPlayingView.m
//  VibratingView
//
//  Created by apple on 2017/9/23.
//  Copyright © 2017年 NetEaseExam. All rights reserved.
//

#import "RLPlayingView.h"

#import "CALayer+AnimationControl.h"

static const NSUInteger instanceCount = 4;
static const CGFloat initialBarWidth = 20.0;
static const NSTimeInterval instanceDelay = 0.1;
static NSString *const animationKeyPath = @"IndicatorAnimation";

@interface RLPlayingView (){
    @private
    BOOL _animating;
    CALayer *_replicator;
    CABasicAnimation *_animation;
}
@end

@implementation RLPlayingView

+ (Class)layerClass{
    return [CAReplicatorLayer class];
}

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        _color = [UIColor grayColor];
        _replicator = [CALayer layer];
        _replicator.allowsEdgeAntialiasing = YES;
        [self.layer addSublayer:_replicator];
        
        CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.scale.y"];
        animation.toValue = @0.1;
        animation.autoreverses = YES;
        animation.repeatCount = HUGE_VALF;
        _animation = animation;
    }
    return self;
}

- (void)layoutSubviews{
    [super layoutSubviews];
    
    CAReplicatorLayer *relayer = (CAReplicatorLayer *)self.layer;
    relayer.instanceCount = instanceCount;
    relayer.instanceTransform = CATransform3DMakeTranslation(self.bounds.size.width/instanceCount, 0, 0);
    relayer.instanceDelay = instanceDelay;
    
    _replicator.anchorPoint = CGPointMake(0.5, 1);
    _replicator.bounds = CGRectMake(0, 0, initialBarWidth, self.bounds.size.height * 0.618);
    _replicator.position = CGPointMake(0.5*(self.bounds.size.width/instanceCount), self.bounds.size.height);    
}

- (void)setColor:(UIColor *)color{
    _color = color;
    _replicator.backgroundColor = _color.CGColor;
}

- (void)startAnimating{
    if ([_replicator animationForKey:animationKeyPath])
    {
        [self.layer ac_resume];
    }
    else
    {
        [_replicator addAnimation:_animation forKey:animationKeyPath];
    }
    _animating = YES;
}

- (void)stopAnimating{
    _animating = NO;
    [self.layer ac_pause];
}

- (BOOL)isAnimating{
    return _animating;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
